package com.ruoyi.web.controller.certificates;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.GlobalConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.YnStatusEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.inspection.constant.InspectionConstant;
import com.ruoyi.system.domain.TemporaryStaffAccount;
import com.ruoyi.system.domain.TemporaryStaffAccountFile;
import com.ruoyi.system.service.TemporaryStaffAccountFileService;
import com.ruoyi.system.service.TemporaryStaffAccountService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 临时施工人员台账(TemporaryStaffAccount)表控制层
 *
 * @author makejava
 * @since 2022-11-18 09:36:47
 */
@RestController
@RequestMapping("temporary/staff/account")
public class TemporaryStaffAccountController extends BaseController {
    @Resource
    private TemporaryStaffAccountService temporaryStaffAccountService;
    @Resource
    private TemporaryStaffAccountFileService temporaryStaffAccountFileService;

    /**
     * 分页查询
     *
     * @return 查询结果
     */
    @GetMapping("list")
    public TableDataInfo queryByPage(TemporaryStaffAccount temporaryStaffAccount) {
        if (null == temporaryStaffAccount.getQueryFlag()) {
            temporaryStaffAccount.setQueryFlag(YnStatusEnum.Y.getCode());
        }
//        startPage();
        List<TemporaryStaffAccount> list = temporaryStaffAccountService.selectList(temporaryStaffAccount);
        if (!CollectionUtils.isEmpty(list)) {
            for (TemporaryStaffAccount account : list) {
                String staffCode = GlobalConstants.COMPANY_CODE + "02"
                        + StrUtil.fill(account.getId()+"", '0', 7, true);
                account.setStaffCode(staffCode);

                List<TemporaryStaffAccountFile> accountFiles = new ArrayList<>();
                String fileId = account.getCertificateFileId();
                if (StringUtils.isNotEmpty(fileId)) {
                    fileId = fileId.substring(0, fileId.length() - 1);
                    if (fileId.contains(",")) {
                        String[] split = fileId.split(",");
                        List<String> id = Arrays.asList(split);
                        if (StringUtils.isNotEmpty(id)) {
                            for (String s : id) {
                                TemporaryStaffAccountFile accountFile = temporaryStaffAccountFileService.queryById(Integer.valueOf(s));
                                accountFiles.add(accountFile);
                            }
                        }
                    } else {
                        TemporaryStaffAccountFile accountFile = temporaryStaffAccountFileService.queryById(Integer.valueOf(fileId));
                        accountFiles.add(accountFile);
                    }
                }
                account.setAccountFileList(accountFiles);
            }
        }


        int total = StringUtils.isEmpty(list) ? 0 : list.size();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageSize = pageDomain.getPageSize();
        Integer pageNum = pageDomain.getPageNum();

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setTotal(total);
        int end = pageNum*pageSize > total ? total : pageNum*pageSize;
        rspData.setRows(list.subList( (pageNum-1)*pageSize, end ) );

        return rspData;
    }

    /**
     * 通过主键查询单条数据
     *
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<TemporaryStaffAccount> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.temporaryStaffAccountService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param temporaryStaffAccount 实体
     * @return 新增结果
     */
    @PostMapping("add")
    @PreAuthorize("@ss.hasPermi('temporary:staff:account:add')")
    public AjaxResult add(@RequestBody TemporaryStaffAccount temporaryStaffAccount) {

        if (StringUtils.isNotEmpty(temporaryStaffAccount.getCardNumber())) {
            TemporaryStaffAccount temporaryStaffAccountReq = new TemporaryStaffAccount();
            temporaryStaffAccountReq.setCardNumber(temporaryStaffAccount.getCardNumber());
            List<TemporaryStaffAccount> temporaryStaffAccounts = temporaryStaffAccountService.selectList(temporaryStaffAccountReq);

            if (!CollectionUtils.isEmpty(temporaryStaffAccounts)) {
                return AjaxResult.error("身份证号信息已经存在。");
            }

        }
        return AjaxResult.success(this.temporaryStaffAccountService.insert(temporaryStaffAccount));
    }

    /**
     * 编辑数据
     *
     * @param temporaryStaffAccount 实体
     * @return 编辑结果
     */
    @PutMapping("edit")
    @PreAuthorize("@ss.hasPermi('temporary:staff:account:edit')")
    public ResponseEntity<TemporaryStaffAccount> edit(@Validated @RequestBody TemporaryStaffAccount temporaryStaffAccount) {
        return ResponseEntity.ok(this.temporaryStaffAccountService.update(temporaryStaffAccount));
    }

    /**
     * 删除数据
     *
     * @param temporaryStaffAccount 主键
     * @return 删除是否成功
     */
    @DeleteMapping("delete")
    @PreAuthorize("@ss.hasPermi('temporary:staff:account:delete')")
    public ResponseEntity<Boolean> deleteById(@Validated @RequestBody TemporaryStaffAccount temporaryStaffAccount) {
        return ResponseEntity.ok(this.temporaryStaffAccountService.deleteById(temporaryStaffAccount.getId()));
    }


    /**
     * 导入
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "临时施工人员", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @PreAuthorize("@ss.hasPermi('temporary:staff:account:importData')")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<TemporaryStaffAccount> util = new ExcelUtil<>(TemporaryStaffAccount.class);
        List<TemporaryStaffAccount> temporaryStaffAccounts = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = temporaryStaffAccountService.importExcel(temporaryStaffAccounts, updateSupport, operName);
        return success(message);
    }

    /**
     * 导出
     *
     * @param response
     */
    @Log(title = "临时施工人员", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @PreAuthorize("@ss.hasPermi('temporary:staff:account:export')")
    public void export(HttpServletResponse response, TemporaryStaffAccount temporaryStaffAccount) {
        List<TemporaryStaffAccount> list = temporaryStaffAccountService.selectList(temporaryStaffAccount);
        ExcelUtil<TemporaryStaffAccount> util = new ExcelUtil<>(TemporaryStaffAccount.class);
        util.exportExcel(response, list, "临时施工人员");
    }

    /**
     * 导入模板
     *
     * @param response
     */
    @PostMapping("/importTemplate")
    @PreAuthorize("@ss.hasPermi('temporary:staff:account:importTemplate')")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<TemporaryStaffAccount> util = new ExcelUtil<>(TemporaryStaffAccount.class);
        util.importTemplateExcel(response, "临时施工人员");
    }


}

